package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.actstartupdata;
import yxy.cherry.data.bean.task;
import yxy.game.pm2.active.module.actcontrol.activeControl;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.subordinateclass.GiftPackage;
import yxy.game.pm2.active.module.subordinateclass.ghost.GhostGachaTask;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.AreaModule;
import yxy.game.pm2.bean.module.PlayerModule;
import yxy.game.pm2.bean.task.Task;
import yxy.game.pm2.module.tip.TipHandle;
import yxy.game.pm2.module.tip.TipType;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ActiveModule_武将直升活动 extends PlayerModule {

    //bean ----------------------------------------------------

    public static final int acttype = 504;

    private int heroId; //活动的武将id

    private ArrayList<GiftPackage> dgifts = new ArrayList<GiftPackage>();//商品

    private HashMap<Integer, GhostGachaTask> taskMap = new HashMap<Integer, GhostGachaTask>();    //武将直升任务

    public ArrayList<GiftPackage> getDgifts() {
        return dgifts;
    }

    public void setDgifts(ArrayList<GiftPackage> dgifts) {
        this.dgifts = dgifts;
    }

    public HashMap<Integer, GhostGachaTask> getTaskMap() {
        return taskMap;
    }

    public void setTaskMap(HashMap<Integer, GhostGachaTask> taskMap) {
        this.taskMap = taskMap;
    }

    public int getHeroId() {
        return heroId;
    }

    public void setHeroId(int heroId) {
        this.heroId = heroId;
    }

    //func ----------------------------------------------------

    /**
     * 创建ActiveModule_武将直升活动
     *
     * @param playerCode
     */
    public static ActiveModule_武将直升活动 create(String playerCode) {
        AreaBean ab = AreaModule.area(playerCode);
        activeControl sai = activeControl.get(ab.getAreaId(), acttype);
        if (sai != null) {
            ActiveModule_武将直升活动 am = new ActiveModule_武将直升活动();
            am.setPlayerCode(playerCode);
            am.setTimeline(sai.getTimeline());
            am.reset();
            am.set();
            return am;
        }
        return null;
    }

    public void update() {
        PlayerBean pb = PlayerBean.get(getPlayerCode());
        ServerBean sb = ServerBean.get(pb.getServerId());
        activeControl sai = activeControl.get(String.valueOf(sb.getAreaId()), String.valueOf(acttype));
        if (sai == null) {
            return;
        }

        // 区活动关闭，但自己活动没关闭，更新活动时间
        if (!sai.running() && running()) {
            setTimeline(sai.getTimeline());
            set();
        }

        // 区活动开启，但自己没开启，重置活动
        if (sai.running() && !running()) {
            setTimeline(sai.getTimeline());
            //重置任务和商品和活动武将等信息
            reset();
            set();
        }
    }

    //重置
    private void reset() {
        Map<String, actstartupdata> agrmap = ActDataCenter.getAllData(actstartupdata.class, getPlayerCode());

        //重置商品
        resetGiftPackage(agrmap);

        //重置任务
        resetTask(agrmap);

        //设置活动的武将id
        actstartupdata actgstartupdata = agrmap.get("1");
        setHeroId(actgstartupdata.getHeroid());
    }


    //重置商品
    private void resetGiftPackage(Map<String, actstartupdata> agrmap) {
        //商城
        setDgifts(new ArrayList<GiftPackage>());
        for (actstartupdata data : agrmap.values()) {
            GiftPackage dgift = new GiftPackage();
            dgift.setId(data.getId());
            dgift.setGoodsid(data.getChargeid());
            dgift.setPackageName(data.getName()); //礼包名称
            dgift.setNumlimit(data.getLimit());//限购次数
            dgift.setBuyNum(0); //已购买次数；
            dgift.setNeedStar(data.getNeedstarlv());//购买需要达到的星级条件
            getDgifts().add(dgift);
        }

    }

    //重置任务
    private void resetTask(Map<String, actstartupdata> agrmap) {

        //清除任务
        for (GhostGachaTask gt : getTaskMap().values()) {
            Task.remove(getPlayerCode(), gt.getTaskcode());
        }

        //重置任务
        setTaskMap(new HashMap<Integer, GhostGachaTask>());
        for (actstartupdata data : agrmap.values()) {
            GhostGachaTask ghostGachaTask = new GhostGachaTask();
            ghostGachaTask.setId(data.getId());
            ghostGachaTask.setTaskid(data.getTaskid());
            ghostGachaTask.setNeedStar(data.getNeedstarlv());
            task taskdata = DataCenter.getData(data.getTaskid(), task.class);
            if (taskdata == null) {
                continue;
            }

            Task taskbean = Task.create(getPlayerCode(), taskdata);
            ghostGachaTask.setTaskcode(taskbean.getCode());
            getTaskMap().put(data.getId(), ghostGachaTask);
        }

    }

    //
    /**
     * 解锁单 加 设置购买时间
     *
     * @param goodsid
     * @param buytime
     */
    public void unlockGiftPackageAndSetBuyTime(int goodsid, DateTime buytime) {
        for (GiftPackage dgift : getDgifts()) {
            if (dgift.getGoodsid() == goodsid) {
                int buyNum = dgift.getBuyNum();
                buyNum++;
                dgift.setBuyNum(buyNum); //修改已购买数量
                set();
            }
        }
    }




    // redis ---------------------------------------------------------

    static private String key(String playerCode) {
        return String.format("PLAYER:%s:ACTIVE:%S", playerCode, acttype);
    }

    public void set() {
        try {
            setv(key(getPlayerCode()), this);
            check();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取 ActiveModule_武将直升活动
     *
     * @param playerCode
     * @return
     */
    public static ActiveModule_武将直升活动 get(String playerCode, Boolean isNewPlayer) {
        try {
            ActiveModule_武将直升活动 module = getv(key(playerCode));
            if (module == null) {

                //新用户不需要去查数据库
                if (!isNewPlayer) {
                    module = MySQLCacheDAO.getV(key(playerCode), ActiveModule_武将直升活动.class);
                    if (module != null) {
                        module.set();
                    }//同步到redis
                }

                if (module == null) {
                    module = create(playerCode);
                }
            }

            module.update();
            module.check();
            return module;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查看是否有可领取奖励 控制红点
     */
    public void check() {
        if (running()) {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.开启);
        } else {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
        }

        if (running()) {
            checkReward();            //检查奖励是否领取
        } else {
            new TipHandle().updateTip(getPlayerCode(), TipType.活动_武将直升, false);
        }
    }

    private void checkReward() {
        for (GhostGachaTask ghostGachaTask : getTaskMap().values()) {
            Task taskbean = Task.get(getPlayerCode(), ghostGachaTask.getTaskcode());
            int canget = taskbean.isReward() ? DrawStatus.hadget.getStatus() : taskbean.isFinish() ? DrawStatus.canget.getStatus() : DrawStatus.cannotget.getStatus();
            if(canget == 1){
                new TipHandle().updateTip(getPlayerCode(), TipType.活动_武将直升, true);
                return;
            }
        }
        new TipHandle().updateTip(getPlayerCode(), TipType.活动_武将直升, false);
    }

    //存储到数据库的方法
    public static void saveToDB(String playerCode) {
        try {
            String key = key(playerCode);
            if (touchBucket(key).isExists()) {
                ActiveModule_武将直升活动 activeModule_武将直升活动 = getv(key(playerCode));
                MySQLCacheDAO.setV(key, activeModule_武将直升活动);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //从redis移走数据的操作
    public static void removeAllFromRedis(String playerCode) {
        try {
            touchBucket(key(playerCode)).delete();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }
    // lock==========================================================================

    @Override
    public String lockKey() {
        return String.format("lock:%s", key(getPlayerCode()));
    }

}
